package indi.wshape1.takeawaydeliveryinfo.servlet;

import indi.wshape1.takeawaydeliveryinfo.domain.*;
import indi.wshape1.takeawaydeliveryinfo.service.UtilService;
import indi.wshape1.takeawaydeliveryinfo.util.StringUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wshape1
 * @create 2022-11-26 9:56
 */

@WebServlet(name = "PageServlet", value = {"/page"})
public class PageServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*  POST    Parameter
            root:   selectedBlock   selectedGroup   selectedType    keyword     page
            admin:  selectedGroup   selectedType    keyword     page
            sender: keyword     page
         */

        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        String user = (String) req.getSession().getAttribute("user");
        if (StringUtil.isEmpty(user))
            return;
        String type = (String) req.getServletContext().getAttribute(user);

        String keyword = req.getParameter("keyword");
        String pageStr = req.getParameter("page");
        int page = 1;
        if (!StringUtil.isEmpty(pageStr))
            page = Integer.parseInt(pageStr);
        String selectedType = req.getParameter("selectedType");

        StringBuilder stringBuilder = new StringBuilder("[{\"type\": \"" + selectedType + "\"},");

        if ("sender".equals(type)) {        /////////////////
            Sender sender = UtilService.senderService.getByPhone(user);
            List<TakeOut> list = UtilService.takeOutService.getListByGroupAndBlockByKeywordAndPage(
                    sender.getGroup(),
                    sender.getBlock(),
                    keyword,
                    page);

            stringBuilder.append(getTakeOutString(list));

        } else if ("admin".equals(type)) {      /////////////////
//            admin:  selectedGroup   selectedType    keyword     page
            String block = UtilService.adminService.getByPhone(user).getBlock();
            String selectedGroup = req.getParameter("selectedGroup");


            if ("takeout".equals(selectedType)) {
                List<TakeOut> list;
                if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.takeOutService.getListByBlockByKeywordAndPage(block, keyword, page);
                } else {
                    list = UtilService.takeOutService.getListByGroupAndBlockByKeywordAndPage(selectedGroup, block, keyword, page);
                }

                stringBuilder.append(getTakeOutString(list));

            } else if ("sender".equals(selectedType)) {
                List<Sender> list;
                if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.senderService.getListByBlockByKeywordAndPage(block, keyword, page);
                } else {
                    list = UtilService.senderService.getListByGroupAndBlockByKeywordAndPage(selectedGroup, block, keyword, page);
                }

                stringBuilder.append(getSenderString(list));

            } else if ("group".equals(selectedType)) {
                List<Group> list;
                if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.groupService.getListByBlockByKeywordAndPage(block, keyword, page);
                } else {
                    list = new ArrayList<>();
                    list.add(UtilService.groupService.getByName(selectedGroup));
                }

                stringBuilder.append(getGroupString(list));

            }


        } else if ("root".equals(type)) {   //////////////////////////
//            root:   selectedBlock   selectedGroup   selectedType    keyword     page
            String selectedBlock = req.getParameter("selectedBlock");
            String selectedGroup = req.getParameter("selectedGroup");

            if ("takeout".equals(selectedType)) {
                List<TakeOut> list;
                if ("-".equals(selectedBlock) || StringUtil.isEmpty(selectedBlock)) {
                    list = UtilService.takeOutService.getListByKeywordAndPage(keyword, page);
                } else if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.takeOutService.getListByBlockByKeywordAndPage(selectedBlock, keyword, page);
                } else {
                    list = UtilService.takeOutService.getListByGroupAndBlockByKeywordAndPage(selectedGroup, selectedBlock, keyword, page);
                }

                stringBuilder.append(getTakeOutString(list));

            } else if ("sender".equals(selectedType)) {
                List<Sender> list;
                if ("-".equals(selectedBlock) || StringUtil.isEmpty(selectedBlock)) {
                    list = UtilService.senderService.getListByKeywordAndPage(keyword, page);
                } else if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.senderService.getListByBlockByKeywordAndPage(selectedBlock, keyword, page);
                } else {
                    list = UtilService.senderService.getListByGroupAndBlockByKeywordAndPage(selectedGroup, selectedBlock, keyword, page);
                }

                stringBuilder.append(getSenderString(list));


            } else if ("admin".equals(selectedType)) {
                List<Admin> list;

                if ("-".equals(selectedBlock) || StringUtil.isEmpty(selectedBlock)) {
                    list = UtilService.adminService.getListByKeywordAndPage(keyword, page);
                } else {
                    list = UtilService.adminService.getListByBlockByKeywordAndPage(selectedBlock, keyword, page);
                }

                for (Admin admin : list) {
                    stringBuilder
                            .append("{\"name\": \"").append(admin.getName())
                            .append("\", \"phone\": \"").append(admin.getPhone())
                            .append("\", \"block\": \"").append(admin.getBlock())
                            .append("\"},");
                }
                if (list.size() > 0)
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            } else if ("group".equals(selectedType)) {
                List<Group> list;
                if ("-".equals(selectedBlock) || StringUtil.isEmpty(selectedBlock)) {
                    list = UtilService.groupService.getListByKeywordAndPage(keyword, page);
                } else if ("-".equals(selectedGroup) || StringUtil.isEmpty(selectedGroup)) {
                    list = UtilService.groupService.getListByBlockByKeywordAndPage(selectedBlock, keyword, page);
                } else {
                    list = new ArrayList<>();
                    list.add(UtilService.groupService.getByName(selectedGroup));
                }

                stringBuilder.append(getGroupString(list));
            } else if ("block".equals(selectedType)) {

                List<Block> list;
                if ("-".equals(selectedBlock) || StringUtil.isEmpty(selectedBlock)) {
                    list = UtilService.blockService.getListByKeywordAndPage(keyword, page);
                } else {
                    list = new ArrayList<>();
                    list.add(UtilService.blockService.getByName(selectedBlock));
                }

                for (Block block : list) {
                    if ("null".equals(block.getName()))
                        continue;
                    stringBuilder
                            .append("{\"name\": \"").append(block.getName())
                            .append("\", \"info\": \"").append(block.getInfo())
                            .append("\"},");
                }
                if (list.size() > 1)
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            }


        }   /////////////////////

        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',')
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("]");
//        System.out.println(stringBuilder);
        writer.print(stringBuilder);
    }

    private StringBuilder getTakeOutString(List<TakeOut> list) {
        StringBuilder stringBuilder = new StringBuilder();
        for (TakeOut takeOut : list) {
            stringBuilder
                    .append("{\"id\": \"").append(takeOut.getId())
                    .append("\", \"name\": \"").append(takeOut.getName())
                    .append("\", \"phone\": \"").append(takeOut.getPhone())
                    .append("\", \"block\": \"").append(takeOut.getBlock())
                    .append("\", \"group\": \"").append(takeOut.getGroup())
                    .append("\", \"time\": \"").append(takeOut.getTimeToString())
                    .append("\", \"sender_phone\": \"").append(takeOut.getSender_phone())
                    .append("\", \"status\": \"").append(takeOut.getStatus().toString())
                    .append("\", \"detail\": \"").append(StringUtil.isEmpty(takeOut.getDetail()) ? "" : takeOut.getDetail())
                    .append("\"},");
        }
        if (list.size() > 0)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        return stringBuilder;
    }

    private StringBuilder getSenderString(List<Sender> list) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Sender sender : list) {
            stringBuilder
                    .append("{\"name\": \"").append(sender.getName())
                    .append("\", \"phone\": \"").append(sender.getPhone())
                    .append("\", \"block\": \"").append(sender.getBlock())
                    .append("\", \"group\": \"").append(sender.getGroup())
                    .append("\"},");
        }
        if (list.size() > 0)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder;
    }

    private StringBuilder getGroupString(List<Group> list) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Group group : list) {
            if ("null".equals(group.getName()))
                continue;
            stringBuilder
                    .append("{\"name\": \"").append(group.getName())
                    .append("\", \"block\": \"").append(group.getBlock())
                    .append("\", \"info\": \"").append(group.getInfo())
                    .append("\"},");
        }
        if (list.size() > 1)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder;
    }


}
